from enum import StrEnum
import json

from core.redis_cache.redis_cache import cache_result
class WeChatAppType(StrEnum):
    """
    应用类型
    """

    WECHAT_MINI_APP = "mini_wechat"
    WECHAT_WEB_APP = "web_wechat"
    WECHAT_OPEN_APP = "open_wechat"

SECRET_KEY = "app_secret"

class WeChatConfigService:
    """
    微信小程序配置服务
    """
    
    file_path = "wechat_config.json"

    @staticmethod
    @cache_result(keys=["tenant_id","wechat_app_id","app_type"],expire=3600)
    def get_wechat_tenant_info(
        tenant_id: str, wechat_app_id: str, app_type: WeChatAppType
    )->str|None:
        """
        获取微信租户信息
        :param tenant_id:
        :return:
        """
        wechat_config = WeChatConfigService.load_config_from_json()
        if not wechat_config:
            return None
        if app_type.value in wechat_config:
            if tenant_id in wechat_config[app_type.value]:
                if wechat_app_id in wechat_config[app_type.value][tenant_id]:
                    return wechat_config[app_type.value][tenant_id][wechat_app_id]
        return None

    @staticmethod
    def load_config_from_json(file_path: str|None=None) -> dict:
        """
        从 JSON 文件加载配置并返回字典
        
        参数:
            file_path: JSON 文件路径
            
        返回:
            包含配置的字典
        """
        if not file_path:
            file_path = WeChatConfigService.file_path
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except FileNotFoundError:
            raise FileNotFoundError(f"配置文件 {file_path} 不存在")
        except json.JSONDecodeError:
            raise ValueError(f"配置文件 {file_path} 格式错误，不是有效的 JSON")

